package thread;

/**
 * Created with IntelliJ IDEA
 * Description：两个线程对同一个变量进行并发的自增
 * User：chenshu
 * Date：2023-11-07
 * Time：18:31
 */
class Counter {
    static int count;

    //相当于对this加锁
    //1.
    /*synchronized public void increase() {
        count++;
    }*/

    //2.
    public void increase(){
        synchronized (this) {
            count++;
        }
    }

    //针对类对象加锁
    //1.
    //synchronized static void func() {}

    //2.
    /*public static void func2() {
        synchronized (Counter.class) {

        }
    }*/
}
public class Demo1 {
    public static void main(String[] args) {
        Counter counter = new Counter();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });
        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //结果是随机数5w～10w
        System.out.println(Counter.count);
    }
}
